/*
 *    Copyright 2022 jacky4631 shen ji email:121659050@qq.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dataoke.shoppingguide.app773026.activity.setting;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.provider.Settings;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.dataoke.shoppingguide.app773026.R;
import com.dataoke.shoppingguide.app773026.activity.PrivacyPolicyActivity;
import com.dataoke.shoppingguide.app773026.activity.update.CheckUpdateManager;
import com.dataoke.shoppingguide.app773026.activity.update.DownloadService;
import com.dataoke.shoppingguide.app773026.base.fragments.BaseFragment;
import com.dataoke.shoppingguide.app773026.bean.Version;
import com.dataoke.shoppingguide.app773026.util.DialogHelper;
import com.dataoke.shoppingguide.app773026.util.FileUtil;
import com.dataoke.shoppingguide.app773026.util.UIHelper;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupAnimation;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 设置界面
 * @author: shen ji
 * @date: 2022/3/15
 * @email: 121659050@qq.com
 * @wechat: jacky4631
 */
public class SettingFragment extends BaseFragment implements
        View.OnClickListener,
        EasyPermissions.PermissionCallbacks,
        CheckUpdateManager.RequestPermissions {

    private static final int RC_EXTERNAL_STORAGE = 0x04;//存储权限

    @BindView(R.id.tv_cache_size)
    TextView mTvCacheSize;
    @BindView(R.id.rl_check_version)
    FrameLayout mRlCheck_version;
    @BindView(R.id.setting_line_bottom)
    View mSettingLineBottom;
    @BindView(R.id.rl_cancel)
    FrameLayout mCancel;

    private Version mVersion;

    public static SettingFragment newInstance() {
        return new SettingFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_setting;
    }

    @Override
    protected void initWidget(View view) {
        super.initWidget(view);

        view.findViewById(R.id.rl_clean_cache).setOnClickListener(this);
        view.findViewById(R.id.rl_about).setOnClickListener(this);
        view.findViewById(R.id.rl_check_version).setOnClickListener(this);
        view.findViewById(R.id.rl_feedback).setOnClickListener(this);
        mCancel.setOnClickListener(this);

    }

    @Override
    protected void initData() {
        super.initData();
        calculateCacheSize();
    }

    @Override
    public void onResume() {
        super.onResume();
        mCancel.setVisibility(View.INVISIBLE);
        mSettingLineBottom.setVisibility(View.INVISIBLE);

    }

    /**
     * 计算缓存的大小
     */
    private void calculateCacheSize() {
        long fileSize = 0;
        String cacheSize = "0KB";
        File filesDir = getActivity().getFilesDir();
        File cacheDir = getActivity().getCacheDir();

        fileSize += FileUtil.getDirSize(filesDir);
        fileSize += FileUtil.getDirSize(cacheDir);
        File externalCacheDir = getActivity().getExternalCacheDir();
        fileSize += FileUtil.getDirSize(externalCacheDir);
        if (fileSize > 0)
            cacheSize = FileUtil.formatFileSize(fileSize);
        mTvCacheSize.setText(cacheSize);
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        switch (id) {
            case R.id.rl_clean_cache:
                onClickCleanCache();
                break;
            case R.id.rl_feedback:
                FeedBackActivity.show(getActivity());
                break;
            case R.id.rl_about:
                AboutActivity.show(mContext);
                break;
            case R.id.rl_check_version:
                Intent intent = new Intent(getContext(), PrivacyPolicyActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_cancel:
                // 清理所有缓存
                UIHelper.clearAppCache(false);
                break;
            default:
                break;
        }

    }

    private void onClickUpdate() {
        CheckUpdateManager manager = new CheckUpdateManager(getActivity(), true);
        manager.setCaller(this);
        manager.checkUpdate(true);
    }

    private void onClickCleanCache() {
        BasePopupView popupView = new XPopup.Builder(getContext())
                .isDestroyOnDismiss(true)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .asConfirm("清空缓存", "是否清空缓存?",
                        "取消", "确定",
                        () -> {
                            UIHelper.clearAppCache(true);
                            mTvCacheSize.setText("0KB");
                        }, null, false);
        popupView.show();
    }

    @Override
    public void call(Version version) {
        this.mVersion = version;
        requestExternalStorage();
    }

    @SuppressLint("InlinedApi")
    @AfterPermissionGranted(RC_EXTERNAL_STORAGE)
    public void requestExternalStorage() {
        if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
            DownloadService.startService(getActivity(), mVersion.getDownloadUrl());
        } else {
            EasyPermissions.requestPermissions(this, "", RC_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
        }
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        DialogHelper.getConfirmDialog(getActivity(), "温馨提示", "需要开启对您手机的存储权限才能下载安装，是否现在开启", "去开启", "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(Settings.ACTION_APPLICATION_SETTINGS));
            }
        }).show();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}
